from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend

from iClouds.Permissions import AllPermissions, MyPermissions
from iClouds.Authentication import MyJWTAuthentication
from iClouds.mktoken import get_tokens_for_user
from iClouds.apidev import filter_views, has_Random

from .serializers import *
from .FilterBackends import *

from mysqldb import sems as SEMS
from mysqldb.serializers import ListDjangoFilterBackend

# Create your views here.


# """初始化管理员"""
# AllinpayUserList.objects.update_or_create(
#     defaults={
#         "name": "超级管理员",
#         "phone": "13896370136",
#         "email": "3361098@qq.com",
#         "is_super": 1,  # 超级
#         "status": 1,  # 状态
#         "is_authenticated": 1,  # 备用
#         "is_active": 1,  # 激活
#         "group": 1,  # 角色
#         "creattime": timezone.now(),
#     },
#     id=1,
# )


# """初始化角色"""
# AllinpayAuthGroup.objects.update_or_create(defaults={"name": "默认角色", "pid": 0}, id=1)


# """初始化经营名目"""
# AllinpayTermList.objects.update_or_create(
#     defaults={"name": "默认营收", "status": 1, "auth": 0}, id=1
# )


def hasPerms(role):
    """返回去重后的合法权限列表，接收参数:角色列表"""
    perms = list(
        AllinpayAuthGroupPermissions.objects.filter(group_id__in=role).values_list(
            "permission_id", flat=True
        )
    )
    return sorted(list(set(perms)), key=perms.index)


def hasRole(user):
    """返回去重后指定用户的角色列表, 接收参数: 用户ID"""
    roles = list(
        AllinpayUserplaceList.objects.filter(uid=user).values_list("group", flat=True)
    )
    return sorted(list(set(roles)), key=roles.index)


def hasUP(user):
    """返回去重后的当前权限列表，接收参数:用户ID"""
    UP = list(
        AllinpayAuthUserPermission.objects.filter(uid=user).values_list(
            "permid", flat=True
        )
    )
    return sorted(list(set(UP)), key=UP.index)


def hasUser():
    """轮询所有用户并检查合法权限, 已禁用"""
    return
    users = AllinpayUserList.objects.all().values_list("id", flat=True)
    for i in users:
        x = hasPerms(hasRole(i))
        p = hasUP(i)
        for j in p:
            if not j in x:
                AllinpayAuthUserPermission.objects.filter(uid=i, permid=j).delete()


class allinpayUserCreatViewSet(viewsets.ModelViewSet):
    __title__ = "注册用户"
    __group__ = "后台用户"
    __doc__ = f"""
    create:\n
    <h4>用户注册</h4>\n
        快速注册新的用户
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayUserCreateSerializer
    queryset = AllinpayUserList.objects.all().order_by("id")

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 验证短信、邮件
        sems = serializer.validated_data.get("password")
        if not settings.DEBUG:
            code = REDIS.redis_get(
                "sems", serializer.validated_data.get("phone"), "code"
            )
            if not code or not sems == code:
                raise serializers.ValidationError({"password": "验证码不能匹配"})
        # 清除短信缓存
        REDIS.redis_del("sems", serializer.validated_data.get("phone"))

        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayUserLoginViewSet(viewsets.ModelViewSet):
    __title__ = "登录用户"
    __group__ = "后台用户"
    __doc__ = f"""
    create:\n
    <h4>登录用户</h4>\n
        快速登录用户
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayUserLoginSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # ...查找用户...
        try:
            phone = AllinpayUserList.objects.get(
                Q(phone=serializer.data["username"])
                | Q(email=serializer.data["username"])
                | Q(openid=serializer.data["username"])
            )
        except BaseException as err:
            raise serializers.ValidationError({"username": "用户不存在"})

        # ...验证方式...
        if serializer.data["act"] == "PASSWORD":
            # 密码验证
            if not settings.DEBUG:
                if not serializer.data["password"] == phone.password:
                    raise serializers.ValidationError({"password": "密码校验错误"})
        else:
            # 验证短信、邮件
            sems = serializer.data["password"]
            if not settings.DEBUG:
                code = REDIS.redis_get("sems", phone.phone, "code")
                if not code or not sems == code:
                    raise serializers.ValidationError({"password": "验证码不能匹配"})
            # 清除短信缓存
            REDIS.redis_del("sems", phone.phone)

        # ...验证属性...
        if not phone.is_active:
            raise serializers.ValidationError({"username": "账户未激活，请自助激活。"})
        if not phone.status:
            raise serializers.ValidationError({"username": "账户已锁定，请联系管理员。"})
        if not phone.is_authenticated:
            raise serializers.ValidationError({"username": "账户已禁用，请联系管理员。"})
        # 创建token
        token = get_tokens_for_user(phone)
        # 记录登录时间
        phone.last_login = timezone.now()
        phone.save()

        # 创建响应数据
        res = Response({"rescode": 200, "resmsg": token["access"]})
        # res["Authorization"] = f'Bearer {token["access"]}'
        return res


class AllinpayUserActivationViewSet(viewsets.ModelViewSet):
    __title__ = "激活用户"
    __group__ = "后台用户"
    __doc__ = f"""
    create:\n
    <h4>激活用户</h4>\n
        快速激活用户
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayUserActivationSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            phone = AllinpayUserList.objects.get(
                Q(phone=serializer.data["username"])
                | Q(email=serializer.data["username"])
                | Q(openid=serializer.data["username"])
            )
        except BaseException as err:
            raise serializers.ValidationError({"username": "用户不存在"})
        # 验证短信
        sems = serializer.data["password"]
        if not settings.DEBUG:
            code = REDIS.redis_get("sems", phone.phone, "code")
            if not code or not sems == code:
                raise serializers.ValidationError({"password": "验证码不能匹配"})
        # 清除短信缓存
        REDIS.redis_del("sems", phone.phone)
        # 激活账号
        phone.is_active = 1
        phone.save()
        return Response(
            {"rescode": 200, "resmsg": serializer.data["username"] + " is Activation"}
        )


class AllinpayUserListSetViewSet(viewsets.ModelViewSet):
    __title__ = "用户信息"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询用户信息列表",
        "patch": "编辑用户信息",
    }
    __doc__ = """
    list:\n
    <h4>用户信息列表</h4>
        用户信息列表
    retrieve:\n
    <h4>用户信息详情</h4>
        用户信息详情
    partial_update:\n
    <h4>用户信息修改</h4>
        用户信息修改
    """
    http_method_names = ["get", "patch"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserListSerializer
    queryset = AllinpayUserList.objects.all()
    # GET 条件过滤
    filter_backends = [SearchFilter]
    # filterset_class = AllinpayQueryInListFilterSet
    # filterset_fields = ["pid", "tid"]
    search_fields = ["name", "phone"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        sess = dict(request.data)
        if "phone" in sess.keys():
            raise serializers.ValidationError({"phone": "该字段禁止编辑"})
        serializer = super().partial_update(request, *args, **kwargs)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayUserStatusSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置用户状态"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>用户状态修改</h4>
        用户状态修改
    """
    http_method_names = [
        "post",
    ]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserStatusSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.data["id"] == request.user.id:
            raise serializers.ValidationError("不能编辑自己")
        instance = self.queryset.get(id=serializer.data["id"])
        instance.status = serializer.data["status"]
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayUserGroupSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置用户后台角色"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>用户角色修改</h4>
        后台用户角色修改
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserGroupSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.data["id"] == request.user.id:
            raise serializers.ValidationError("不能编辑自己")
        instance = self.queryset.get(id=serializer.data["id"])
        instance.group = serializer.data["group"]
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayUserActiveSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置用户激活"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>用户激活修改</h4>
        用户激活修改
    """
    http_method_names = [
        "post",
    ]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserActiveSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.data["id"] == request.user.id:
            raise serializers.ValidationError("不能编辑自己")
        instance = self.queryset.get(id=serializer.data["id"])
        instance.is_active = serializer.data.get("is_active")
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayUserBackstSetViewSet(viewsets.ModelViewSet):
    __title__ = "用户后台登录"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>用户后台登录修改</h4>
        用户后台登录权限修改
    """
    http_method_names = [
        "post",
    ]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserBackstSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.data["id"] == request.user.id:
            raise serializers.ValidationError("不能编辑自己")
        instance = self.queryset.get(id=serializer.data["id"])
        instance.is_authenticated = serializer.data.get("is_authenticated")
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayUserSuperSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置用户超级"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>用户超级编辑</h4>
        用户超级编辑
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserSuperSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.data["id"] == request.user.id:
            raise serializers.ValidationError("不能编辑自己")
        instance = self.queryset.get(id=serializer.data["id"])
        instance.is_super = serializer.data.get("is_super")
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayAuthGroupSetViewSet(viewsets.ModelViewSet):
    __title__ = "后台角色"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询后台角色列表",
        "post": "创建后台角色",
        "patch": "编辑后台角色",
        "delete": "移除后台角色",
    }
    __doc__ = """
    list:\n
    <h4>后台角色列表</h4>
    retrieve:\n
    <h4>后台角色详情</h4>
    create:\n
    <h4>后台角色</h4>
    partial_update:\n
    <h4>后台角色编辑</h4>
    delete:\n
    <h4>后台角色移除</h4>
        后台角色移除,会移除场所内拥有该角色的用户绑定关系。
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayAuthGroupSerializer
    queryset = AllinpayAuthGroup.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        sess = dict(request.data)
        if "pid" in sess.keys():
            raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        serializer = super().partial_update(request, *args, **kwargs)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.id == 1:
            raise serializers.ValidationError("不能移除默认设置")
        self.perform_destroy(instance)
        # 清除已经分配用户
        AllinpayUserplaceList.objects.filter(group=instance.id).delete()
        # 清空该角色权限
        AllinpayAuthGroupPermissions.objects.filter(group_id=instance.id).delete()
        # 检查合法权限
        hasUser()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayAuthGroupPermissionsSetViewSet(viewsets.ModelViewSet):
    __title__ = "角色权限"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询后台角色权限列表",
        "post": "创建后台角色权限",
        "delete": "移除后台角色权限",
    }
    __doc__ = """
    list:\n
    <h4>角色权限列表</h4>
        角色权限列表
    retrieve:\n
    <h4>角色权限详情</h4>
        角色权限详情
    create:\n
    <h4>角色权限</h4>
        创建角色权限
        不能给默认角色创建任何权限
    delete:\n
    <h4>角色权限移除</h4>
        角色权限移除
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayAuthGroupPermissionsSerializer
    queryset = AllinpayAuthGroupPermissions.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["group_id"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        # 检查合法权限
        hasUser()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayAuthViewsSetViewSet(viewsets.ModelViewSet):
    __title__ = "所有视图"
    __group__ = "后台用户"
    __doc__ = """
    list:\n
    <h4>所有视图列表</h4>        
        staff: 视图作用域因数
        1: 后台视图
        2: 员工视图
        4: 未启用
        8: 未启用
        16: 未启用
    retrieve:\n
    <h4>所有视图详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayAuthViewsSerializer
    queryset = AllinpayAuthViews.objects.all()
    # GET 条件过滤

    filter_backends = [ListDjangoFilterBackend]
    filterset_class = AllinpayAuthViewsFilterSet

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayAuthUserPermissionSetViewSet(viewsets.ModelViewSet):
    __title__ = "用户权限"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询后台用户权限列表",
        "post": "创建后台用户权限",
        "delete": "移除后台用户权限",
    }
    __doc__ = """
    list:\n
    <h4>用户权限列表</h4>
        用户权限列表
    retrieve:\n
    <h4>用户权限详情</h4>
        用户权限详情
    create:\n
    <h4>用户权限</h4>
        创建用户权限
    delete:\n
    <h4>用户权限移除</h4>
        用户权限移除
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayAuthUserPermissionSerializer
    queryset = AllinpayAuthUserPermission.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["uid", "pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPasswordSetViewSet(viewsets.ModelViewSet):
    __title__ = "修改指定用户密码"
    __group__ = "后台用户"
    __doc__ = """
    create:\n
    <h4>修改指定用户密码</h4>
        修改指定用户密码
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPasswordSerializer
    queryset = AllinpayUserList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        AllinpayUserList.objects.filter(id=serializer.data["id"]).update(
            password=serializer.data["password"]
        )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayUserBankSetViewSet(viewsets.ModelViewSet):
    __title__ = "用户银行卡"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询用户银行卡列表",
        "post": "创建用户银行卡",
        "patch": "编辑用户银行卡",
        "delete": "移除用户银行卡",
    }
    __doc__ = """
    list:\n
    <h4>用户银行卡</h4>
        列表用户银行卡
    retrieve:\n
    <h4>用户银行卡</h4>
        详情用户银行卡, 根据记录ID查询
    create:\n
    <h4>用户银行卡</h4>
        创建用户银行卡
    partial_update:\n
    <h4>用户银行卡</h4>
        修改用户银行卡
    delete:\n
    <h4>用户银行卡</h4>
        移除用户银行卡
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserBankSerializer
    queryset = AllinpayUserBank.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["userid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        # partial = False
        # instance = self.get_object()
        # serializer = self.get_serializer(instance, data=request.data, partial=partial)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        sess = dict(request.data)
        if "userid" in sess.keys():
            raise serializers.ValidationError({"userid": "该字段禁止编辑"})
        serializer = super().partial_update(request, *args, **kwargs)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayUserobjectListViewSet(viewsets.ModelViewSet):
    __title__ = "用户对象列表"
    __group__ = "后台用户"
    __info__ = {
        "get": "查询用户指定门店列表",
        "post": "创建用户指定门店",
        "put": "工作项统计报表编辑",
        "delete": "移除用户指定门店",
    }
    __doc__ = """
    list:\n
    <h4>用户对象列表</h4>
    retrieve:\n
    <h4>用户对象详情</h4>
    create:\n
    <h4>创建用户对象列表</h4>
    delete:\n
    <h4>移除用户对象列表</h4>
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayUserobjectListSerializer
    queryset = AllinpayUserobjectList.objects.all()

    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["uid", "pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# 检查视图
# from iClouds.apidev import filter_views
filter_views(globals())
